package com.zjs.express.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

public class WXLoginCheckFilter implements Filter {
    // 添加你自己的静态资源路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/css/*", "/js/*", "/images/*",
            "/layer/*", "/qrcode/*", "/wx/wximages/*",
            "/wx/login.do", "/wx/toLogin.do", "/wx/login.html"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //设置编码
        httpServletRequest.setCharacterEncoding("UTF-8");
        String requestURI = httpServletRequest.getRequestURI();
        String contextPath = httpServletRequest.getContextPath();
        String url = requestURI.substring(contextPath.length());

        // 检查请求的URL是否在白名单中
        if (WHITE_LIST.stream().anyMatch(pattern -> matchesPattern(url, pattern))) {
            // 允许请求继续
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取session
        Object wxUser = httpServletRequest.getSession().getAttribute("wxUser");
        //登录成功
        if (wxUser != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //跳到登录界面
            //提示请登录后再试！
            httpServletResponse.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write("<!DOCTYPE html><html><head><title>Redirect</title></head><body>");
            writer.write("<script>");
            writer.write("alert('请您登录后，再试试哦^^！');");
            writer.write("window.location.href='" + httpServletRequest.getContextPath() + "/wx/toLogin.do';");
            writer.write("</script>");
            writer.write("</body></html>");
        }
    }

    private boolean matchesPattern(String uri, String pattern) {
        // 简单的模式匹配，支持通配符 *
        if (pattern.endsWith("/*")) {
            return uri.startsWith(pattern.substring(0, pattern.length() - 2));
        } else {
            return uri.equals(pattern);
        }
    }

    @Override
    public void destroy() {
    }
}
